package cn.edu.pzhu.javaweb.controller;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.edu.pzhu.javaweb.dao.UserDao;
import cn.edu.pzhu.javaweb.dao.imp.UserDaoImp;
import cn.edu.pzhu.javaweb.pojo.Result;
import cn.edu.pzhu.javaweb.pojo.User;
import cn.edu.pzhu.javaweb.service.UserService;
import cn.edu.pzhu.javaweb.service.imp.UserServiceImp;
import cn.edu.pzhu.javaweb.util.Conver2MD5;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private UserService userService = new UserServiceImp();
    private UserDao userDao = new UserDaoImp();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 response.setContentType("text/html");
		    String username = request.getParameter("username");
		    String password = request.getParameter("password");
		    
		    if(username == null || username.isEmpty() || password == null || password.isEmpty()) {
		        response.getWriter().print("<script>alert('信息不完整!');location.href='login.jsp';</script>");
		        return;
		    }
		    
		    String sec_password = Conver2MD5.getSHA256(Conver2MD5.getSHA256(username+password)+"pzhu");
		    User user = new User(username, sec_password, null);
		    Result<String> result = userService.login(user);

		    if (result.getCode() == 200) {
		        String isSave = request.getParameter("save");
		        if (isSave == null || isSave.isEmpty()) {
		            // 没有勾选，不保存密码，并且清除原来保存的密码
		            Cookie usernameCookie = new Cookie("username", "");
		            usernameCookie.setMaxAge(0);
		            response.addCookie(usernameCookie);

		            Cookie passwordCookie = new Cookie("password", "");
		            passwordCookie.setMaxAge(0);
		            response.addCookie(passwordCookie);

		            Cookie saveCookie = new Cookie("save", "");
		            saveCookie.setMaxAge(0);
		            response.addCookie(saveCookie);
		        } else {
		            // 保存密码7天
		            Cookie usernameCookie = new Cookie("username", username);
		            usernameCookie.setMaxAge(7 * 24 * 60 * 60);
		            response.addCookie(usernameCookie);

		            Cookie passwordCookie = new Cookie("password", password);
		            passwordCookie.setMaxAge(7 * 24 * 60 * 60);
		            response.addCookie(passwordCookie);

		            Cookie saveCookie = new Cookie("save", "yes");
		            saveCookie.setMaxAge(7 * 24 * 60 * 60);
		            response.addCookie(saveCookie);
		        }
		    }
		    
		    
		    if (result.getCode() == 200) {
		    	// 获取或创建session
		        HttpSession session = request.getSession();
		        
		        // 设置会话超时时间（30分钟）
		        session.setMaxInactiveInterval(30 * 60);
		        
		        // 从数据库获取完整的用户信息
        User dbUser = userDao.selectById(username);
        
        // 存储用户信息到session
        session.setAttribute("user", dbUser);  // 添加user对象到session
        session.setAttribute("username", username);
        session.setAttribute("loginTime", new Date());
		        
		        // 验证session是否设置成功
		        System.out.println("登录成功，Session ID: " + session.getId());
		        System.out.println("设置的username: " + session.getAttribute("username"));
		        
		        response.getWriter().print("<script>alert('登录成功!');location.href='index.jsp';</script>");
		    } else {
		    	String errorMsg = result.getMsg() != null ? result.getMsg() : "登录失败";
		        response.getWriter().print("<script>alert('" + errorMsg+ "');location.href='login.jsp';</script>");
		    }
		
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
